#include <stdio.h>
#include <stdlib.h>

#include <new>
#include <string>
#include <ios>
#include <iostream>
#include <vector>
#include <stdexcept>
#include <iostream>
#include <cstdlib>

#include <config.h>

#ifdef HAVE_LIBCGICC
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
using namespace cgicc;
#else
#include <cgi.h>
#endif

#include "geoip.h"

#include <GeoIPCity.h>
#include <GeoIP.h>

#include <assert.h>


using namespace std;

int main(int argc, char **argv)
{
	try {
		float lat = 0, lon = 0;
#ifdef HAVE_LIBCGICC
		Cgicc cgi;
		const CgiEnvironment& env = cgi.getEnvironment();

		init_geoip();
		getLatLongByIp(env.getRemoteAddr().c_str(), &lat, &lon);
		close_geoip();

		cout << HTTPContentHeader("text/xml; charset=utf-8");
#else
		s_cgi *cgi;
		cgi = cgiInit();

		init_geoip();
		getLatLongByIp(getenv("REMOTE_ADDR"), &lat, &lon);
		close_geoip();

		//cgiSetHeader("Content-Type", "text/xml; charset=utf-8");
		cgiSetType("text/xml; charset=utf-8");
		cgiHeader();
#endif
		cout << "<?xml version='1.0' encoding=\"utf-8\"?>" << endl;
		cout.setf(ios_base::fixed, ios_base::floatfield);
		cout.precision(10);
		cout << "<location>" << "<latitude>" << lat << "</latitude><longitude>" << lon << "</longitude>" << "</location>" << endl;
	} catch (const std::exception& e) {
#ifdef HAVE_LIBCGICC
		cout << HTTPHTMLHeader() << HTMLDoctype(HTMLDoctype::eStrict) << endl;
#else
		cgiHeader();
		cout << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">" << endl;
#endif
		cout << "<html><head></head><body>" << e.what() << "</body></html>" << endl;
	}
	exit(0);
}
